package com.ayh.campusfun.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.ayh.campusfun.common.APIResult;
import com.ayh.campusfun.service.CaptchaService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.apache.axis.encoding.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ayh
 * @create 2021/3/23 0023 13:58
 * 验证码接口实现类
 */

@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public String getCaptcha() {
        //获取验证码文本内容
        String text = defaultKaptcha.createText();
        // 创建输出流对象变量
        ByteArrayOutputStream outputStream = null;
        //根据文本内容创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(text);

        Map<String, Object> map = new HashMap<String, Object>();
        try {
            outputStream = new ByteArrayOutputStream();
            //输出流输出图片,格式为jpg
            ImageIO.write(image,"jpg",outputStream);
            // 生成captcha的token
            map.put("imgBase64", "data:image/jpg;base64," + Base64.encode(outputStream.toByteArray()));
            String captchaKey = RandomUtil.randomString(10);
//            缓存到redis中，设置超时时间
            redisTemplate.opsForValue().set(captchaKey,text,60 * 3, TimeUnit.SECONDS);
            map.put("captchaKey",captchaKey);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return APIResult.successData(map);
    }
}
